import request from '../request'
import { API_ENDPOINTS } from '../config'

// 数据源类型
export type DataSourceType = 'auto' | 'ugc' | 'manual' | 'pr'

// 数据源状态
export type DataSourceStatus = 'connected' | 'disconnected' | 'warning'

// 数据源信息
export interface DataSource {
  id: string
  type: DataSourceType
  name: string
  description: string
  status: DataSourceStatus
  config: {
    host?: string
    port?: number
    database?: string
    username?: string
    syncMode?: string
    frequency?: string
  }
  stats: {
    todayAdded: number
    todayFailed: number
    totalRecords: number
    lastSyncTime: string
  }
  connectionDetails: {
    latency?: string
    nextSync?: string
    importMethod?: string
  }
}

// 同步日志
export interface SyncLog {
  id: string
  sourceType: DataSourceType
  action: string
  status: 'success' | 'error' | 'warning'
  message: string
  timestamp: string
  details?: any
}

// 数据源统计
export interface DataSourceStats {
  totalSources: number
  connectedSources: number
  todaySync: number
  todayErrors: number
  totalRecords: number
}

// 同步参数
export interface SyncParams {
  force?: boolean
  batchSize?: number
  timeout?: number
}

// 连接测试结果
export interface ConnectionTestResult {
  success: boolean
  latency: number
  message: string
  details: {
    network: boolean
    authentication: boolean
    database: boolean
    permissions: boolean
  }
}

// 数据整合 API 服务
export const dataIntegrationApi = {
  // 获取所有数据源
  getSources() {
    return request.get<DataSource[]>(API_ENDPOINTS.DATA_INTEGRATION.SOURCES)
  },

  // 获取指定数据源详情
  getSourceDetail(type: DataSourceType) {
    return request.get<DataSource>(`${API_ENDPOINTS.DATA_INTEGRATION.SOURCES}/${type}`)
  },

  // 同步数据源
  syncData(type: DataSourceType, params?: SyncParams) {
    const url = API_ENDPOINTS.DATA_INTEGRATION.SYNC.replace(':type', type)
    return request.post<{
      taskId: string
      message: string
      estimatedTime: number
    }>(url, params)
  },

  // 测试数据源连接
  testConnection(type: DataSourceType) {
    const url = API_ENDPOINTS.DATA_INTEGRATION.TEST_CONNECTION.replace(':type', type)
    return request.post<ConnectionTestResult>(url)
  },

  // 获取同步日志
  getLogs(params?: {
    sourceType?: DataSourceType
    status?: 'success' | 'error' | 'warning'
    startTime?: string
    endTime?: string
    page?: number
    pageSize?: number
  }) {
    return request.get<{
      list: SyncLog[]
      total: number
      page: number
      pageSize: number
    }>(API_ENDPOINTS.DATA_INTEGRATION.LOGS, params)
  },

  // 获取数据源统计
  getStats() {
    return request.get<DataSourceStats>(API_ENDPOINTS.DATA_INTEGRATION.STATS)
  },

  // 更新数据源配置
  updateSourceConfig(type: DataSourceType, config: Partial<DataSource['config']>) {
    return request.put<DataSource>(`${API_ENDPOINTS.DATA_INTEGRATION.SOURCES}/${type}/config`, config)
  },

  // 启用/禁用数据源
  toggleSource(type: DataSourceType, enabled: boolean) {
    return request.post(`${API_ENDPOINTS.DATA_INTEGRATION.SOURCES}/${type}/toggle`, { enabled })
  },

  // 获取同步任务状态
  getSyncTaskStatus(taskId: string) {
    return request.get<{
      taskId: string
      status: 'pending' | 'running' | 'completed' | 'failed'
      progress: number
      message: string
      startTime: string
      endTime?: string
      result?: any
    }>(`/sync-tasks/${taskId}`)
  },

  // 取消同步任务
  cancelSyncTask(taskId: string) {
    return request.post(`/sync-tasks/${taskId}/cancel`)
  },

  // 上传 Excel 文件（人工采购系统）
  uploadExcel(file: File) {
    return request.upload<{
      taskId: string
      recordCount: number
      message: string
    }>('/data-sources/manual/upload', file)
  },

  // 批量录入 PR 记录
  batchCreatePRRecords(records: Array<{
    articleUrl: string
    backlinkUrl: string
    platform: string
    quality: number
    notes?: string
  }>) {
    return request.post<{
      successCount: number
      failedCount: number
      errors: string[]
    }>('/data-sources/pr/batch-create', { records })
  },

  // 导出数据源数据
  exportSourceData(type: DataSourceType, format: 'xlsx' | 'csv' = 'xlsx') {
    return request.download(
      `/data-sources/${type}/export?format=${format}`,
      `${type}-data.${format}`
    )
  },

  // 获取数据源健康状态
  getSourceHealth() {
    return request.get<Array<{
      type: DataSourceType
      status: DataSourceStatus
      lastCheck: string
      issues: string[]
      recommendations: string[]
    }>>('/data-sources/health')
  },
}